package com.sixbro.caicaitv;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.os.Bundle;

import java.util.ArrayList;
import java.util.List;

public class BaseAppContext extends Application {
    private static BaseAppContext sInstance;//全局上下文对象
    private Activity mCurActivity; //当前顶部Activity
    private List<Activity> mActivityList = new ArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
        registerActivityLifecycleCallbacks(new MyActivityLifecycleCallbacks());
        if (!BuildConfig.DEBUG) {
            Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    quitApp();
                }
            });
        }
    }

    @Override
    public void onTrimMemory(int level) {
        if (!isAppForeground(this)) {
            //应用在后台时的逻辑
            quitApp();
        }
        super.onTrimMemory(level);
    }

    //判断APP是否在前台
    private boolean isAppForeground(Context context) {
        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(Service.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfoList =
                activityManager.getRunningAppProcesses();
        if (runningAppProcessInfoList == null) {
            //在后台
            return false;
        }

        for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcessInfoList) {
            if (processInfo.processName.equals(context.getPackageName())
                    && (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)) {
                //在前台
                return true;
            }
        }
        //在后台
        return false;
    }

    public static BaseAppContext getInstance() {
        return sInstance;
    }

    public static Context getContext() {
        return sInstance.getApplicationContext();
    }

    private class MyActivityLifecycleCallbacks implements ActivityLifecycleCallbacks {

        @Override
        public void onActivityCreated(Activity activity, Bundle bundle) {
            mCurActivity = activity;
            mActivityList.add(activity);
        }

        @Override
        public void onActivityStarted(Activity activity) {
        }

        @Override
        public void onActivityResumed(Activity activity) {
            mCurActivity = activity;
        }

        @Override
        public void onActivityPaused(Activity activity) {
        }

        @Override
        public void onActivityStopped(Activity activity) {
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            mActivityList.remove(activity);
        }
    }

    /**
     * 获取当前的Activity
     *
     * @return
     */
    public Activity getCurActivity() {
        return mCurActivity;
    }

    /**
     * 获取程序中有某个activity，null代表没有
     */
    public Activity getActivity(Class<?> cls) {
        for (Activity activity : mActivityList) {
            if (cls.getName().equals(activity.getClass().getName())) {
                return activity;
            }
        }
        return null;
    }

    /**
     * 是否是当前Acitivity
     */
    public boolean isCurActivity(Class<?> cls) {
        if (mCurActivity == null) {
            return false;
        }
        return mCurActivity.getClass().getName().equals(cls.getName());
    }

    /**
     * 关闭指定Activity
     *
     * @param cls
     */
    public void finshActivity(Class<?>... cls) {
        for (Class<?> item : cls) {
            Activity activity = getActivity(item);
            if (activity != null) {
                activity.finish();
            }
        }
    }

    public List<Activity> getActivityList() {
        return mActivityList;
    }

    public void quitApp() {
        try {
            for (Activity activity : mActivityList) {
                if (activity != null)
                    activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }
}
